import ApiApp from "@/api/app";
import useFetch from "./useFetch";
import { computed, reactive, shallowRef, watch } from "vue";

type TCategory = {
  id: number;
  title: string;
  p_id: number;
  children?: TCategory[];
};

let categoryMap;

const transToMap = (list: TCategory[]) => {
  list.forEach((e) => {
    categoryMap.set(e.id, e);
    if (e.children && e.children?.length > 0) {
      transToMap(e.children);
    }
  });
};

const useGetCategory = () => {
  const listMap = reactive(categoryMap ?? new Map());
  categoryMap = listMap;

  const list = shallowRef<TCategory[]>([]);
  const { data } = useFetch<{ list: TCategory[] }>(ApiApp.getCategoryTree);

  watch(data, (val) => {
    list.value = val.list;
    transToMap(val.list);
  });

  return {
    list,
    listMap
  };
};

export default useGetCategory;
